/*
 * Author: Luciano Hoult
 * Contact: lucianolee@zju.edu.cn
 * Company: Zhejiang University
 * Created Date: Tuesday December 3rd 2019 3:57:56 pm
 * Last Modified: Sunday January 12th 2020 5:43:28 pm
 */


//Display a prompt to add

function prompt_add() {
  var prompt_text;
  var name_add = prompt("Please enter your name:", "John Doe");
  //If no name or cancelled:
  if (name_add == null || name_add == "") {
    prompt_text = "User cancelled the prompt.";
  } else {
    // If name is valid, read fingerprint.
    prompt_text = "Now put your finger on the scanner, " + name_add + ".";
    alert(prompt_text);
  }

  //Create a new HTTP request for later communication
  var xhttp = new XMLHttpRequest();

  //If we get a response from server:
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      //valid response, then interprete
      var res_obj = JSON.parse(this.responseText);
      var res_int = res_obj.result;
      //log response for debug convenience
      console.log(res_obj);
      console.log(res_int);
      if (res_int == 1) {
        alert("Completed.");
      } else {
        alert("Failed. Refer to log file for more info.");
      }
    }
  }
  
  //Use GET method, tell the server to add & send the name
  xhttp.open("GET", "http://127.0.0.1:8000/fp_add?name=" + name_add, true);
  xhttp.send();
}

//Display a prompt to delete after specification

function prompt_del() {
  var prompt_text;
  var name_del = prompt("Please specify name or number:", "");
  if (name_del == null || name_del == "") {
    prompt_text = "User cancelled the prompt.";
  } else {
    prompt_text = "Now deleting the fingerprint of " + name_del + ".";
    alert(prompt_text);
  }

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var res_obj = JSON.parse(this.responseText);
      var res_int = res_obj.result;
      if (res_int == 1) {
        alert("Completed.");
      } else {
        alert("Failed. Refer to log file for more info.");
      }
    }
  }

  xhttp.open("GET", "http://127.0.0.1:8000/fp_del?name=" + name_del, true);
  xhttp.send();
}

//Display a prompt to check for a match

function prompt_chk() {
  var prompt_text = "Now put your finger on the scanner.";
  alert(prompt_text);

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var res_obj = JSON.parse(this.responseText);
      var res_int = res_obj.result;
      if (res_int == 2) {
        alert("Completed. Your fingerprint is a match.");
      } else if (res_int == 1) {
        alert("Completed but there's no match of your fingerprint.");
      }
    }
  }
  xhttp.open("GET", "http://127.0.0.1:8000/fp_chk", true);
  xhttp.send();
}
